<template>
  <div class="education-video">
    <div class="video-header">
      <h2>{{ resourceName }}</h2>
      <div class="rating">
        <span class="score">{{ rating }}分</span>
      </div>
    </div>

    <div class="like-rating-favorite">
      <div>
        <button style="border: none; background: none; cursor: pointer;color: #ef7f7f" @click="likeVideo">
          <i :class="['icon', userLiked ? 'fas fa-heart' : 'far fa-heart']"></i>
        </button>
      </div>
      <div>{{ likeCount }}</div>
      <div>
        <button style="border: none; background: none; cursor: pointer;color: #f6d83f" @click="toggleFavorite">
          <i :class="['icon', isFavorited ? 'fas fa-star' : 'far fa-star']"></i>
        </button>
      </div>
      <div>{{ favoriteCount }}</div>
    </div>

    <div v-if="success">
        <img :src="videoUrl" type="video/mp4" alt="资源加载失败"/>
    </div>
    <div v-else class="error-message">
      加载视频失败，请稍后重试或联系支持。
    </div>

    <div class="description">
      感谢所有为资源建设提供资料的单位和个人。未经允许不得转载或引用。
    </div>
    <div>{{ resourceDescription }}</div>

    <!-- Element Plus 评分组件 -->
    <div class="rating-input">
      <el-rate v-model="newRating" :max="5" :clearable="false"></el-rate>
      <el-button type="primary" @click="submitRating">提交评分</el-button>
    </div>
  </div>
</template>

<script>
import { cosApi, resourceApi } from '@/api/resourceApi';
import axios from 'axios';
import { useUserStore } from "@/store/useUserStore.ts";

import { ElRate, ElButton } from 'element-plus'; // 导入 Element Plus 组件

// 获取 CSRF Token
function getCsrfToken() {
  const name = 'XSRF-TOKEN=';
  const decodedCookie = decodeURIComponent(document.cookie);
  const cookies = decodedCookie.split(';');
  for (let i = 0; i < cookies.length; i++) {
    const cookie = cookies[i].trim();
    if (cookie.indexOf(name) === 0) {
      return cookie.substring(name.length, cookie.length);
    }
  }
  console.warn('CSRF Token not found in cookies');
  return '';
}

export default {
  name: 'EducationVideoComponent',
  components: {
    ElRate,
    ElButton
  },
  props: {
    resourceId: {
      type: Number,
      required: true
    },
  },

  data() {
    return {
      videoUrl: '',
      resourceName: '',
      resourceDescription: '',
      success: false,
      favoriteCount: 0,   // 收藏总数
      likeCount: 0,       // 点赞总数
      rating: 0,          // 平均评分

      userLiked: false,   // 用户是否已点赞
      isFavorited: false, // 用户是否已收藏
      newRating: 0        // 新评分
    };
  },

  computed: {
    userInfo() {
      const userStore = useUserStore();
      return userStore.userInfo;
    }
  },

  methods: {
    async fetchData() {
      try {
        const resourceData = await resourceApi.getbyId(this.resourceId);
        this.resourceName = resourceData.data.resourceName || '无标题';
        this.resourceDescription = resourceData.data.resourceDescription || '无描述';
        this.videoUrl = (await cosApi.playObject(this.resourceName)).data;

        await this.fetchCounts();
        await this.checkUserLikeStatus();
        await this.checkUserFavoriteStatus();

        this.success = true;
      } catch (error) {
        console.error('数据获取失败', error);
        this.success = false; // 显示加载失败信息
      }
    },

    async fetchCounts() {
      try {
        const [favoriteResponse, likeResponse, ratingResponse] = await Promise.all([
          axios.get("http://localhost:8000/favorites/count", {params: {resourceId: this.resourceId}}),
          axios.get(`http://localhost:8000/likes/count/${this.resourceId}`),
          axios.get("http://localhost:8000/ratings/average", {params: {resourceId: this.resourceId}})
        ]);

        this.favoriteCount = favoriteResponse.data.data || 0;
        this.likeCount = likeResponse.data.data || 0;
        this.rating = ratingResponse.data || 0;

      } catch (error) {
        console.error('获取计数失败', error);
      }
    },

    async checkUserLikeStatus() {
      try {
        const response = await axios.get("http://localhost:8000/likes/check", {
          params: {
            userId: this.userInfo.id,
            resourceId: this.resourceId
          }
        });
        this.userLiked = response.data.data === true;
      } catch (error) {
        console.error('检查用户点赞状态失败', error);
      }
    },

    async checkUserFavoriteStatus() {
      try {
        const response = await axios.get("http://localhost:8000/favorites/status", {
          params: {
            Id: this.userInfo.id,
            resourceId: this.resourceId
          }
        });
        this.isFavorited = response.data.data === true;
      } catch (error) {
        console.error('检查用户收藏状态失败', error);
      }
    },

    async likeVideo() {
      try {
        if (!this.userInfo || !this.userInfo.id) {
          console.error('用户信息不可用');
          return;
        }
        if (this.userLiked) {
          await axios.delete("http://localhost:8000/likes", {
            params: {
              resourceId: this.resourceId,
              Id: this.userInfo.id
            }
          });
          this.likeCount--;
          this.userLiked = false;
        } else {
          await axios.post("http://localhost:8000/likes", {
            resourceid: this.resourceId,
            id: this.userInfo.id,
            likestatus: 1
          });
          this.likeCount++;
          this.userLiked = true;
        }
      } catch (error) {
        console.error('更新点赞状态失败', error);
      }
    },

    async toggleFavorite() {
      try {
        if (this.isFavorited) {
          await axios.delete("http://localhost:8000/favorites", {
            params: {
              resourceId: this.resourceId,
              Id: this.userInfo.id
            }
          });
          this.favoriteCount--;
          this.isFavorited = false;
        } else {
          await axios.post("http://localhost:8000/favorites", {
            resourceid: this.resourceId,
            id: this.userInfo.id,
            favoritestatus: 1
          });
          this.favoriteCount++;
          this.isFavorited = true;
        }
      } catch (error) {
        console.error('更新收藏状态失败', error);
      }
    },

    async submitRating() {
      if (!this.userInfo || !this.userInfo.id) {
        console.error('用户信息不可用');
        return;
      }

      if (this.newRating < 0 || this.newRating > 5) {
        console.error('评分必须在0到5之间');
        return;
      }

      try {
        // 提交评分
        const response = await axios.post('/ratings', {
          resourceid: this.resourceId,
          id: this.userInfo.id,
          score: this.newRating
        }, {
          headers: {
            'X-XSRF-TOKEN': getCsrfToken() // 添加 CSRF Token
          }
        });

        // 更新评分信息
        this.rating = response.data.score; // 假设后端返回新的平均评分
        this.newRating = 0; // 清空输入框

      } catch (error) {
        console.error('评分提交失败', error);
      }
    }
  },

  async created() {
    await this.fetchData();
  }
};
</script>

<style scoped>
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css');

.education-video {
  font-family: Arial, sans-serif;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #f9f9f9;
}

.video-header {
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.video-header h2 {
  font-size: 24px;
  color: #333;
}

.rating {
  color: #f90;
}

.like-rating-favorite {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.icon {
  font-size: 20px;
  margin-right: 5px;
  cursor: pointer;
}

.description {
  font-size: 14px;
  margin-top: 10px;
  color: #666;
}

.description + div {
  margin-top: 10px;
}

.rating-input {
  margin-top: 15px;
  display: flex;
  align-items: center;
}
</style>
